package handler.commandprocessor;

import dao.ClientDAO;
import handler.CommandHandler;
import io.netty.channel.ChannelHandlerContext;
import message.Command;
import message.command.RegisterCommand;
import message.receive.RegisterReceive;
import route.Router;
import util.Constants;

public class RegisterProcessor implements CommandHandler.CommandProcessor
{
    private ClientDAO clientDAO;
    private Router    router;

    public RegisterProcessor(ClientDAO clientDAO, Router router)
    {
        this.clientDAO = clientDAO;
        this.router = router;
    }

    @Override
    public void process(Command command, ChannelHandlerContext ctx)
    {
        String          registerName    = ((RegisterCommand) command).getRegisterName();
        RegisterReceive registerReceive = new RegisterReceive();
        try
        {
            String clientId = clientDAO.saveClient(registerName);
            router.clientOnline(clientId, ctx.channel());
            registerReceive.setCode((byte) 0);
            registerReceive.setCodeMsg("注册成功");
            ctx.channel().attr(Constants.CLIENT_ID).set(clientId);
            ctx.channel().attr(Constants.CLIENT_NAME).set(registerName);
        }
        catch (Exception e)
        {
            registerReceive.setCode((byte) 1);
            registerReceive.setCodeMsg("客户端标识已经存在");
        }
        ctx.channel().writeAndFlush(registerReceive);
    }
}
